<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use fast\Arr;
use fast\Http;
use think\Db;

/**
 * 入金订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\common\model\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\order\Order;
        $this->view->assign("cardtypeList", $this->model->getCardtypeList());
        $this->view->assign("tradetypeList", $this->model->getTradetypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        $tradeType = input("trade_type",'');
        if (!$tradeType){
            $this->error("参数不全");
        }
        $admin = Db::name("admin")->where('id',$this->auth->id)->find();
        $mechId = $admin['mechId'];
        $appId = $admin['appId'];

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $map = [];
            $map['tradeType'] = $tradeType;
            if ($this->auth->id != 1){
                $map['store_id'] = $this->auth->id;
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['id','username','nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function huidiao()
    {
        $tradeType = input("trade_type",'');
        if (!$tradeType){
            $this->error("参数不全");
        }
        //查询订单 重发请求

        $this->success();
    }
    protected $mechId = "10001119";
    protected $appId = "2000001117";
    protected $md5Key = "HV3Aex2lnVn0eFGJHlXRHOKKsnb4mAvA";
//    protected $mechId = "10001114";
//    protected $appId = "2000001114";
//    protected $md5Key = "CvpZywDhauci3Le2j15MySd2YiFkltCr";

    /**
     * 重出
     */
    public function reappear($id = null){
        $order = $this->model->where('id', $id)->find();
        if(!$order) return $this->error("订单不存在");
        // TODO validate
        if($order->tradeType != 2){
            return $this->error("订单类型错误");
        }

        $url = 'https://api.taijinnet.com/gateway/kj/agencyPay';
        $params = [
            'channelCode'   =>  'tmkj1',
            'outTradeNo'    =>  $order->outTradeNo,
            'subject'       =>  $order->subject,
            'txnAmount'     =>  $order->txnAmount,
            'charge'    =>  $order->charge,
            'notifyUrl' =>  request()->domain().'/api/kj/notify_agencypay',
            'certNo'    =>  $order->certNo,
            'memberName'    =>  $order->memberName,
            'cardType'  =>  $order->cardType,
            'cardNo'    =>  $order->cardNo,
            'phoneNo'   =>  $order->phoneNo,
            'cvn2'  =>  $order->cvn2,
            'validDate' =>  $order->validDate,
        ];

        $public = [
            'mechId' => $this->mechId,
            'appId' => $this->appId,
            'timestamp' => date("Y-m-d H:i:s"),
            'nonceStr' => md5(uniqid()),
            'version' => '1.0',
            'signMethod' => 'md5',
        ];
        $params = array_merge($params,$public);
        dump($params);
        $params["sign"] = $this->createSign($params, $this->md5Key);
        $header = [
            CURLOPT_HTTPHEADER=>["content-type: application/json","charset=UTF-8"]
        ];
        $response = Http::post($url,json_encode($params),$header);
        $res = json_decode($response,true);
        dump($res);
        if(Arr::get($res, 'respCode') == "TC0000"){
            return $this->success('重出成功');
        }
        return $this->error($response,null, $res);
    }

    private function createSign($params, $md5Key) {
        // 过滤空参数
        $params = array_filter($params, function($value) {
            return !is_null($value) && $value !== '';
        });
        ksort($params); // 按参数名升序排序
        $stringToSign = '';
        foreach ($params as $key => $value) {
            if ($key != 'sign' && $value != '') {
                $stringToSign .= $key . '=' . $value . '&';
            }
        }
        $stringToSign = trim($stringToSign,'&').$md5Key;
        return md5($stringToSign);
    }

}
